﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PodcastToMP3
{
    public class Mp4IEnumerator : IEnumerator<IAtom>
    {
        private static string[] dataAtoms = { "mvhd", "mdat" };

        public long Start { get; set; }
        public long End { get; set; }
        public System.IO.Stream BaseStream { get; set; }

        private IAtom Parent { get; set; }
        private long? Index { get; set; }

        public Mp4IEnumerator(System.IO.Stream baseStream, IAtom Parent, long start, long end)
        {
            this.BaseStream = baseStream;
            this.Parent = Parent;
            if (Parent.Parent != null)
                this.Start = start + 8;
            else
                this.Start = start;
            this.End = end;
        }

        public IAtom Current
        {
            get
            {
                return new Atom(this.BaseStream, Parent, this.Index.Value);
            }
        }

        public void Dispose()
        {
            this.BaseStream = null;
        }

        object System.Collections.IEnumerator.Current
        {
            get { return this.Current; }
        }

        public bool MoveNext()
        {
            if (dataAtoms.Contains(Parent.Name))
                return false;

            if (!this.Index.HasValue)
                this.Index = this.Start;
            else
                this.Index = Current.End;
            return this.Index < this.End;

        }

        private void Contains(string p)
        {
            throw new NotImplementedException();
        }

        public void Reset()
        {
            this.Index = null;
        }
    }
}
